package com.party.web.biz.activity;

import cn.jpush.api.utils.StringUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ApplyInput;
import com.party.core.model.activity.ApplyOutput;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.distributor.DistributorDetail;
import com.party.core.model.distributor.DistributorDetailType;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.member.ThirdPartyUser;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderStatus;
import com.party.core.model.order.OrderType;
import com.party.core.model.order.Output.OrderOutput;
import com.party.core.model.order.PaymentWay;
import com.party.core.model.order.input.BookOrderInput;
import com.party.core.model.store.StoreGoods;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.IThirdPartyUserService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.store.IStoreGoodsService;
import com.party.core.service.system.ISysConfigService;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.pay.model.refund.AliPayRefundResponse;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.pay.service.refund.RefundOrderBizService;
import com.party.web.biz.copartner.BrokerageBizService;
import com.party.web.biz.copartner.MemberCopartnerDetailBizService;
import com.party.web.biz.distribution.DistributionBizService;
import com.party.web.biz.merchantAnalyze.MemberMerchantDetailBizService;
import com.party.web.biz.order.OrderBizService;
import com.party.web.biz.refund.MessageOrderBizService;
import com.party.web.biz.refund.RefundBizService;
import com.party.web.web.dto.output.activity.MemberActOutput;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 活动报名业务处理
 */
@Service
public class MemberActBizService {

    @Autowired
    private IMemberActService memberActService;
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private PayOrderBizService payOrderBizService;
    @Autowired
    private MessageOrderBizService messageOrderBizService;
    @Autowired
    private OrderActivityBizService orderActivityBizService;
    @Autowired
    private RefundOrderBizService refundOrderBizService;
    @Autowired
    private RefundBizService refundBizService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IGatherProjectService gatherProjectService;
    @Autowired
    private IGatherFormService gatherFormService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private OrderBizService orderBizService;
    @Autowired
    private IStoreGoodsService storeGoodsService;
    @Autowired
    private IDistributorDetailService distributorDetailService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    private DistributionBizService distributorBizService;
    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;
    @Autowired
    private IBrokerageItemService brokerageItemService;
    @Autowired
    private BrokerageBizService brokerageBizService;
    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;
    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private IThirdPartyUserService thirdPartyUserService;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 审核通过——免费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return
     */
    public boolean verifyPassFree(String memberActId, String activityId) {
        try {
            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());

            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);

            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                payOrderBizService.updatePayBusiness(memberAct.getOrderId());
                messageOrderBizService.paySend(memberAct.getOrderId());
            } else {
                CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(memberActId);
                payOrderBizService.updatePayBusiness2(OrderType.ORDER_ACTIVITY.getCode(), null, activityId, memberAct.getMemberId(), counterfoilBusiness.getCounterfoilId());
                messageOrderBizService.sendFree(OrderType.ORDER_ACTIVITY.getCode(), activityId, memberActId, memberAct.getMemberId());
            }
            return true;
        } catch (Exception e) {
            logger.error("免费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核通过——收费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return
     */
    public boolean verifyPassNoFree(String memberActId, String activityId) {
        try {
            Activity activity = activityService.get(activityId);
            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    // 如果订单状态等于已退款，则重新生成订单信息
                    if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                        String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                        memberAct.setOrderId(orderId);
                    } else {
                        orderActivityBizService.updateActivityOrderStatus(memberAct.getOrderId(), OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    }
                } else {
                    String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    memberAct.setOrderId(orderId);
                }
            } else {
                String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                memberAct.setOrderId(orderId);
            }
            memberActService.update(memberAct);

            notifySendService.sendApplyPass(activity, memberAct.getId(), memberAct.getMobile(), memberAct.getMemberId(), ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            return true;
        } catch (Exception e) {
            logger.error("收费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核拒绝——免费
     */
    public boolean verifyFailFree(String memberActId, String activityId) {
        try {
            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);

            // 如果是线下活动, 拒绝的时候, 如果已经是设置为已付款了, 那钱也要减少
            if (memberAct.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode()) && MemberAct.PAY_STATUS_YES.equals(memberAct.getPayStatus())) {
                try {
                    String actId = memberAct.getActId();
                    Activity act = activityService.get(actId);
//                    memberPersonalCountBizService.updateActivityNumMoney(act.getMember(), memberAct.getMemberId(), memberAct.getPayment(), false);
                    PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(act.getMember(), memberAct.getMemberId());
                    memberPersonalCountBizService.countOne(partnerMember);
                } catch (Exception e) {
                    logger.error("实时更新活动报名金额/数量异常 ", e);
                }
            }

            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 其它
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);
            // 免费活动
            refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, null);
            messageOrderBizService.freeActivityRejectSend(memberActId, activityId, memberAct.getMemberId());
            return true;
        } catch (Exception e) {
            logger.error("免费活动审核拒绝异常:{}", e);
            return false;
        }
    }

    /**
     * 审核拒绝——收费
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyFailNoFree(String memberActId) {
        try {
            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            memberActService.update(memberAct);

            OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
            if (StringUtils.isEmpty(memberAct.getOrderId()) || orderForm == null) {
                refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, null);
                messageOrderBizService.freeActivityRejectSend(memberActId, memberAct.getActId(), memberAct.getMemberId());
                return true;
            } else {
                // 更改订单状态 其它
                if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {
                    Object responseData = refundBizService.refund(orderForm.getId());
                    if (responseData != null) {
                        if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
                            AliPayRefundResponse response = (AliPayRefundResponse) responseData;
                            // 状态码等于10000表示成功
                            if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                                return refundBizService.activityRefundCallback(orderForm.getId(), response, PaymentWay.ALI_PAY.getCode());
                            }
                        } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                            WechatPayRefundResponse response = (WechatPayRefundResponse) responseData;
                            // 退款成功
                            if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode()) && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                                return refundBizService.activityRefundCallback(orderForm.getId(), response, PaymentWay.WECHAT_PAY.getCode());
                            }
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("收费活动审核拒绝异常", e);
            return false;
        }
    }

    public SXSSFWorkbook exportExcel(List<MemberActOutput> memberActOutputs, String activityId) {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet0 = wb.createSheet("报名人员信息导出");
        appenCell(memberActOutputs, sheet0, activityId);
        return wb;
    }

    private void appenCell(List<MemberActOutput> memberActOutputs, Sheet sheet, String activityId) {
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        df.applyPattern("#.##");
        String[] memberInfoTitles = new String[]{
                "活动名称", "参与者昵称", "联系人", "公司", "职位", "身份证", "手机号", "微信号", "备注"
        };
        String[] applyInfoTitles = new String[]{
                "票据类型", "票据名称", "金额", "状态", "签到", "报名时间", "付款备注"
        };
        String[] fieldsTitle = null;

        GatherProject gatherProject = gatherProjectService.findByTargetId(activityId);
        if (null != gatherProject) {
            List<GatherForm> gatherForms = gatherFormService.findByProjectId(gatherProject.getId());
            List<String> formFields = LangUtils.transform(gatherForms, GatherForm::getTitle);
            fieldsTitle = formFields.toArray(new String[formFields.size()]);
        }
        Row titleRow = sheet.createRow(0);
        // 基本信息
        for (int i = 0; i < memberInfoTitles.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(memberInfoTitles[i]);
        }
        // 附属信息
        if (null != fieldsTitle) {
            for (int i = 0; i < fieldsTitle.length; i++) {
                Cell cell = titleRow.createCell(i + memberInfoTitles.length);
                cell.setCellValue(fieldsTitle[i]);
            }
        }
        int fieldLength = null == gatherProject ? 0 : fieldsTitle.length;

        // 票据信息
        for (int i = 0; i < applyInfoTitles.length; i++) {
            Cell cell = titleRow.createCell(i + memberInfoTitles.length + fieldLength);
            cell.setCellValue(applyInfoTitles[i]);
        }


        for (int i = 0; i < memberActOutputs.size(); i++) {
            Row row = sheet.createRow(i + 1);
            MemberActOutput output = memberActOutputs.get(i);

            // 基本信息
            String[] memberInfoValues = new String[]{
                    output.getActivityTitle(), null == output.getMember() ? "" : output.getMember().getRealname(),
                    output.getName(), output.getCompany(), output.getJobTitle(), output.getIdCard(), output.getMobile(),
                    output.getWechatNum(), output.getExtra()
            };

            for (int j = 0; j < memberInfoValues.length; j++) {
                Cell c0 = row.createCell(j);
                c0.setCellValue(memberInfoValues[j]);
            }

            if (null != gatherProject) {
                // 附属信息
                Map<String, Object> params = Maps.newHashMap();
                params.put("projectId", gatherProject.getId());
                params.put("targetId", output.getId());
                List<Map<String, Object>> gatherFormInfos = gatherFormInfoService.webListPage(params, null);
                for (int k = 0; k < gatherFormInfos.size(); k++) {
                    Map<String, Object> map = gatherFormInfos.get(k);
                    String[] fieldValues = null != map.get("fieldValue")
                            ? map.get("fieldValue").toString().split("maxIndex") : new String[0];
                    System.out.println();


                    for (int p = 0; p < fieldValues.length; p++) {
                        Cell c0 = row.createCell(p + memberInfoTitles.length);
                        c0.setCellValue(fieldValues[p]);
                    }
                }
            }

            // 票据信息
            String[] applyInfoValues = new String[]{
                    output.getCounterType(), output.getCounterName(), df.format(output.getCounterPrice()), output.getCheckStatusName(),
                    output.getSignInName(), DateUtils.formatDate(output.getCreateTime(), "yyyy-MM-dd HH:mm"), output.getRemarks()
            };

            for (int j = 0; j < applyInfoValues.length; j++) {
                Cell c0 = row.createCell(j + memberInfoTitles.length + fieldLength);
                c0.setCellValue(applyInfoValues[j]);
            }
        }
    }
    @Transactional
    public ApplyOutput getApplyData4(String memberId, ApplyInput applyInput, GatherProject project, Counterfoil counterfoil) throws BusinessException {
        /**
         * 1、如果报名为收费，则再次报名生成新记录，对应新订单
         * 2、如果报名来自分销，则再次报名生成新记录，因为不能一条报名记录，对应多条分销关系
         * 3、如果报名为免费或者线下付费，则再次找之前生成的对应记录，没有则生成
         */
        applyInput.setPayment(counterfoil.getPayment());
        applyInput.setCounterName(counterfoil.getName());
        applyInput.setCounterType(counterfoil.getType());

        ApplyOutput applyOutput = new ApplyOutput();

        Activity activity = activityService.get(applyInput.getId());

        if (sysConfigService.isOpenExpirationRestriction()) {
            boolean isExpire = MemberFormUtil.isExpire(activity.getMember(), null);
            if (isExpire) {
                throw new BusinessException("该商户歇业中，无法报名");
            }
        }

        boolean isNew = true;

        if (CounterfoilType.TYPE_FREE.getCode().equals(counterfoil.getType())
                || CounterfoilType.TYPE_OFF_LINE.getCode().equals(counterfoil.getType())) {
            // 如果票据为免费或者为线下付费 没有记录则生成，有则更新
            MemberAct dbMemberAct = memberActService.getMyActFree(memberId, applyInput.getId(), counterfoil.getType());
            if (null == dbMemberAct) {
                applyOutput = insertApply4(memberId, applyInput, activity);
            } else {
                if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                    throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
                }
                updateApply4(applyInput, counterfoil.getType(), applyOutput, dbMemberAct);

                isNew = false;
            }
        } else {
            MemberAct dbMemberAct = memberActService.getMyActNoFree(memberId, applyInput.getId());
            if (null == dbMemberAct) {
                applyOutput = insertApply4(memberId, applyInput, activity);
            } else {
                if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                    throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
                }
                DistributorDetail detail = distributorDetailService.findByTargetId(dbMemberAct.getId());
                if (null != detail || CounterfoilType.TYPE_ON_LINE.getCode().equals(counterfoil.getType())) {
                    // 分销详情不为空，说明来自分销，需要生成新记录
                    // 如果为收费票据，需要生成新记录
                    applyOutput = apply3(applyInput, memberId);
                } else {
                    updateApply4(applyInput, counterfoil.getType(), applyOutput, dbMemberAct);

                    isNew = false;
                }
            }
        }

        if (null != project.getInfoItems()) {
            try {
                gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getGatherFormProjectId(), memberId, applyOutput.getMemberActId(), isNew);
            } catch (Exception e) {
                logger.error("保存自定义信息异常", e);
            }
        }

        if (null == applyInput.getDistributionType()) {
            applyInput.setDistributionType(DistributorRelationType.ACTIVITY.getCode());
        }

        String memberActId = applyOutput.getMemberActId();
        // 处理分销
        new Thread(() -> dealDistribution(applyInput, memberActId, memberId)).start();

        // 0元活动 自动报名成功 免费或者线下支付
        if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                applyInput.getCounterType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
            try {
                payOrderBizService.updatePayBusiness2(applyInput.getOrderType(), applyInput.getFrom(), applyInput.getId(), memberId, applyInput.getCounterfoilId());
                messageOrderBizService.sendFree(applyInput.getOrderType(), applyInput.getId(), applyOutput.getMemberActId(), memberId);
            } catch (Exception e) {
                logger.error("免费活动回调异常", e);
            }

            new Thread(() -> {
                if (OrderType.ORDER_ACTIVITY.getCode().equals(applyInput.getOrderType())) {
                    try {
                        memberMerchantDetailBizService.updateApplyNum(activity.getMember());
                    } catch (Exception e) {
                        logger.error("实时更新机构报名统计数异常", e);
                    }

                    // 只有免费活动才直接+1, 线下活动要手动点确认付款了才+1
                    if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
                        try {
                            PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), memberId);
                            memberPersonalCountBizService.countOne(partnerMember);
                        } catch (Exception e) {
                            logger.error("实时更新个人活动报名数量异常", e);
                        }
                    }
                }
            }).start();
            applyOutput.setActStatus(ActStatus.ACT_STATUS_PAID.getCode());
            applyOutput.setActId(applyInput.getId());
            applyOutput.setFrom(applyInput.getFrom());
        }

        // 票据处理
        Integer joinNum = counterfoil(applyOutput.getMemberActId(), applyInput.getCounterfoilId(), memberId);
        applyOutput.setJoinNum(joinNum);

        return applyOutput;
    }
    /**
     * 活动报名
     * @param input 输入视图
     * @param memberId 会员编号
     * @return 报名输出视图
     */
    @Transactional
    public ApplyOutput apply3(ApplyInput input, String memberId) {
        ApplyOutput applyOutput = new ApplyOutput();

        // 生成报名数据
        MemberAct memberAct = new MemberAct();
        memberAct.setActId(input.getId());
        memberAct.setMemberId(memberId);
        memberAct.setName(input.getRealname());
        memberAct.setMobile(input.getMobile());
        memberAct.setCompany(input.getCompany());
        memberAct.setJobTitle(input.getTitle());
        memberAct.setExtra(input.getExtra());
        memberAct.setWechatNum(input.getWechatNum());
        memberAct.setPayment(input.getPayment());
        memberAct.setCounterfoilName(input.getCounterName()); // 票据名称
        memberAct.setCounterfoilType(input.getCounterType()); // 票据类型
        memberAct.setUpdateBy(memberId);
        memberAct.setJoinin(YesNoStatus.YES.getCode());// 报名
        memberAct.setCollect(YesNoStatus.YES.getCode());
        memberAct.setPayStatus(MemberAct.PAY_STATUS_NO); // 没有付款
        //后台报名
        memberAct.setApplyFrom(MemberAct.APPLY_FROM_BACKSTAGE);

        List<ThirdPartyUser> userList = thirdPartyUserService.getByMemberId(memberId);

        if (userList == null || userList.size() <= 0)
        {
            //手机号和微信未进行授权关联
            memberAct.setIsBindphone(1);
        }

        // 审核状态已审核
        memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
        BaseModel.preByInfo(memberId, memberAct);
        memberActService.insert(memberAct);

        // 0元活动不生成订单 线上支付才生成订单
        if (input.getCounterType().equals(CounterfoilType.TYPE_ON_LINE.getCode())) {
            // 生成订单数据
            BookOrderInput bookOrderInput = orderBizService.createBookOrder(input);
            OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
            // 将订单Id放入报名表
            memberAct.setOrderId(orderOutput.getId());
            memberActService.update(memberAct);
            applyOutput.setOrderId(orderOutput.getId());
        }

        // 属于分享连接
        if (!Strings.isNullOrEmpty(input.getStoreGoodsId())) {
            // 统计成交量
            StoreGoods storeGoods = storeGoodsService.get(input.getStoreGoodsId());
            Integer num = storeGoods.getApplyNum();
            storeGoods.setApplyNum(num + 1);
            storeGoodsService.update(storeGoods);
        }

        applyOutput.setMemberActId(memberAct.getId());
        applyOutput.setActStatus(memberAct.getCheckStatus());

        return applyOutput;
    }
    /**
     * 报名处理分销
     *
     * @param applyInput  请求参数
     * @param memberActId 报名记录id
     * @param memberId    用户id
     */
    public void dealDistribution(ApplyInput applyInput, String memberActId, String memberId) {
        try {
            //分销统计
            DistributorRelation distributorRelation
                    = distributorRelationService.get(applyInput.getDistributionType(),
                    applyInput.getDistributorTargetId(), applyInput.getDistributorId());
            if (null != distributorRelation) {
                Integer findCount = 0;

                MemberAct query = new MemberAct();
                query.setMemberId(memberId);
                query.setActId(applyInput.getId());
                List<MemberAct> memberActs = memberActService.list(query);
                for (MemberAct item : memberActs) {
                    DistributorDetail applyDetail = distributorDetailService.get(item.getId()
                            , DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode(), distributorRelation.getId());
                    if (null != applyDetail) {
                        findCount++;
                        distributorDetailService.delete(applyDetail.getId());
                    }
                }

                DistributorDetail distributorDetail = new DistributorDetail();
                distributorDetail.setTargetId(memberActId);
                distributorDetail.setDistributorRelationId(distributorRelation.getId());
                distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode());
                distributorDetailService.insert(distributorDetail);

                // 如果已经保存分销详情，就不用再保存
                if (findCount == 0) {
                    distributorBizService.distributorCount(distributorRelation.getId(), DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode());

                    try {
                        memberCopartnerDetailBizService.updateApplyNum(memberActId);
                    } catch (Exception e) {
                        logger.error("实时更新合伙人报名统计数异常", e);
                    }
                }

                findCount = 0;
                for (MemberAct item : memberActs) {
                    List<BrokerageItem> brokerageItems = brokerageItemService.findByTargetId(item.getId());
                    if (null != brokerageItems && brokerageItems.size() > 0) {
                        for (BrokerageItem brokerageItem : brokerageItems) {
                            BrokerageItem t = new BrokerageItem();
                            t.setId(brokerageItem.getId());
                            t.setTargetId(memberActId);
                            brokerageItemService.update(t);
                        }
                        findCount++;
                        break;
                    }
                }

                // 免费的课程处理佣金
                try {
                    if (CounterfoilType.TYPE_FREE.getCode().equals(applyInput.getCounterType())
                            && OrderType.ORDER_COURSE.getCode().equals(applyInput.getOrderType())) {
                        if (findCount == 0) {
                            brokerageBizService.insertBrokerageItem(memberActId, applyInput.getId(), BrokerageItem.TYPE_COURSE, memberId);
                        }
                    }
                } catch (Exception e) {
                    logger.error("免费的课程处理佣金异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("报名的分销统计异常", e);
        }
    }
    /**
     * 删除已有的票据，增加新的票据
     * @param memberActId
     * @param counterfoilId
     * @param memberId
     */
    public Integer counterfoil(String memberActId, String counterfoilId, String memberId) {
        counterfoilBusinessService.deleteByBusinessId(memberActId);
        CounterfoilBusiness search = new CounterfoilBusiness(counterfoilId, memberActId);
        CounterfoilBusiness business = counterfoilBusinessService.getUnique(search);
        if (business == null) {
            search.setCreateBy(memberId);
            counterfoilBusinessService.insert(search);
        }

        Counterfoil counterfoil = counterfoilService.get(counterfoilId);
        counterfoil.setJoinNum(counterfoil.getJoinNum() + 1);
        counterfoilService.update(counterfoil);

        Activity activity = activityService.get(counterfoil.getBusinessId());
        activity.setJoinNum(activity.getJoinNum() + 1);
        activityService.update(activity);

        return activity.getJoinNum();
    }

    /**
     * 更新报名信息
     *
     * @param applyInput      报名信息
     * @param counterfoilType 票据类型
     * @param applyOutput     报名输出信息
     * @param dbMemberAct     报名记录
     * @return
     * @author yifeng
     * @date 9:45 2019/10/12
     **/
    private void updateApply4(ApplyInput applyInput, Integer counterfoilType, ApplyOutput applyOutput, MemberAct dbMemberAct) {
        dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode()); // 更改为“已审核”状态
        dbMemberAct.setJoinin(YesNoStatus.YES.getCode());
        dbMemberAct.setName(applyInput.getRealname()); // 联系人
        dbMemberAct.setMobile(applyInput.getMobile()); // 手机
        dbMemberAct.setCompany(applyInput.getCompany()); // 公司名称
        dbMemberAct.setJobTitle(applyInput.getTitle()); // 公司职位
        dbMemberAct.setExtra(applyInput.getExtra()); // 备注信息
        dbMemberAct.setPayment(applyInput.getPayment()); // 活动费用
        dbMemberAct.setCounterfoilName(applyInput.getCounterName()); // 票据名称
        dbMemberAct.setCounterfoilType(applyInput.getCounterType()); // 票据类型
        dbMemberAct.setWechatNum(applyInput.getWechatNum()); // 微信号
        dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_NO); // 没有付款
        dbMemberAct.setRemarks("");
        dbMemberAct.setCreateDate(new Date());
        dbMemberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        //后台报名
        dbMemberAct.setApplyFrom(MemberAct.APPLY_FROM_BACKSTAGE);
        if (!CounterfoilType.TYPE_ON_LINE.getCode().equals(counterfoilType)) {
            dbMemberAct.setOrderId("");
        }
        memberActService.update(dbMemberAct);// 更新报名信息

        applyOutput.setMemberActId(dbMemberAct.getId());
        applyOutput.setActStatus(dbMemberAct.getCheckStatus());
        applyOutput.setOrderId(dbMemberAct.getOrderId());
    }

    /**
     * 新增报名记录
     *
     * @param memberId   用户id
     * @param applyInput 报名信息
     * @param activity   活动信息
     * @return
     * @author yifeng
     * @date 9:44 2019/10/12
     **/
    private ApplyOutput insertApply4(String memberId, ApplyInput applyInput, Activity activity) {
        ApplyOutput applyOutput;// 第一次报名
        applyOutput = apply3(applyInput, memberId);

        // 不是免费数据就个人统计表添加数据, 因为免费数据在下面实时更新个人活动报名数量的时候已经个人统计表添加数据
        if (!applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
            memberPersonalCountBizService.getSet(activity.getMember(), memberId);
        }
        return applyOutput;
    }
}
